<?php

namespace app\admin\controller\ques;

use app\common\controller\Backend;
use think\Db;
/**
 * 问卷调查-题目管理
 *
 * @icon fa fa-circle-o
 */
class Subject extends Backend
{
    
    /**
     * Subject模型对象
     * @var \app\admin\model\ques\Subject
     */
    protected $model = null;
    public $answer_name = ['A','B','C','D','E'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ques\VolumeSubject;
        $this->Datamodel = new \app\admin\model\ques\VolumeSubjectData;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index($ids = null){
        
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $this->assign('ids',$ids);
        if ($this->request->isAjax()){
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')){
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            
           // print_r($this->model->getLastSql());die;
            $list = collection($list)->toArray();
                //print_R($list);die;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
     /**
     * 添加
     */
    public function add($ids = null){
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
           
                if($params['type'] == 1){
                   if(!isset($params['type1'])) $this->error("请填写答案");
                   $type1 = $params['type1'];
                   if(!isset($type1['status'])) $this->error("请选择一个正确答案");
                   $status = $params['type1']['status'];
                   unset($params['type1'],$type1['status']);
               }elseif($params['type'] == 2){
                    if(!isset($params['type2'])) $this->error("请填写答案");
                   $type2 = $params['type2'];
                   if(!$type2['status'][0]) $this->error("请选择一个正确答案");
                   $status = implode($params['type2']['status'], ',');
                   unset($params['type2'],$type2['status']);
               }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                 //开启事务操作
                 Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                         if($params['type'] == 1){
                            if($type1){
                                foreach ($type1 as $k =>&$param) {
                                    $param['subject_id'] = $this->model->id;
                                    if($k == $status){
                                       $param['status'] = 2;
                                    }
                                }
                                $this->Datamodel->saveAll($type1);
                            }
                        }elseif($params['type'] == 2){
                            if($type2){
                                foreach ($type2 as $k =>&$param) {
                                    $param['subject_id'] = $this->model->id;
                                    if(ValueExists($k,$status)){
                                       $param['status'] = 2;
                                    }
                                }
                                $this->Datamodel->saveAll($type2);
                            }
                        }
                          // 提交事务
                        Db::commit();
                        $this->success();
                    } else {
                          // 回滚事务
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                      // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('ids',$ids);
        $this->assign('answer_name',$this->answer_name);

        $this->assign('TypeList',$this->model->getTypeList());
        return $this->view->fetch();
    }
   /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
       
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if($params['type'] == 1){
                    if(!isset($params['type1'])) $this->error("请填写答案");
                    $type1 = $params['type1'];
                    if(!isset($type1['status'])) $this->error("请选择一个正确答案");
                    $type1 = $params['type1'];
                    $status = $params['type1']['status'];
                    unset($params['type1'],$type1['status']);
                }elseif($params['type'] == 2){
                    if(!isset($params['type2'])) $this->error("请填写答案");
                   $type2 = $params['type2'];
                   if(!$type2['status'][0]) $this->error("请选择一个正确答案");
                   $status = implode($params['type2']['status'], ',');
                   unset($params['type2'],$type2['status']);
               }

                 //开启事务操作
                 Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    if ($result !== false) {
                        if($params['type'] == 1){
                            if($type1){
                                $result = model(GetTableModel('VolumeSubjectData'))->where('subject_id','=',$ids)->delete();
                                foreach ($type1 as $k =>&$param) {
                                    $param['subject_id'] = $ids;
                                    if($k == $status){
                                       $param['status'] = 2;
                                    }
                                }
                             
                                $this->Datamodel->saveAll($type1);
                            }
                        }elseif($params['type'] == 2){
                            if($type2){
                                $result = model(GetTableModel('VolumeSubjectData'))->where('subject_id','=',$ids)->delete();
                                foreach ($type2 as $k =>&$param) {
                                    $param['subject_id'] = $ids;
                                    if(ValueExists($k,$status)){
                                       $param['status'] = 2;
                                    }
                                }
                                $this->Datamodel->saveAll($type2);
                            }
                        }
                          // 提交事务
                        Db::commit();
                        $this->success();
                    } else {
                         // 回滚事务
                        Db::rollback();
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                     // 回滚事务
                        Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $type1 = collection($this->Datamodel->where(['subject_id'=>$ids])->select())->toArray();   
        $this->assign('TypeList',$this->model->getTypeList());
        $this->view->assign("type1", $type1);
        $this->view->assign("type2", $type1);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}   
